import { cwbbData } from './cwbbData.js';
import { asyncSetInterval, currentToTaxindex, saveTableDetail } from '../../lib/zeroReportUtils.js';
let zeroInfo;
let kjzzDm = {
  1: '执行企业会计准则',
  3: '执行小企业会计准则'
};
let bbType = {
  zcfzb: '资产负债表',
  lrb: '利润表',
  xjllb: '现金流量表'
};
let inputIds = {
  xqykjzz: {
    zcfzb: 'sb29806001vo',
    lrb: 'sb29806002vo',
    xjllb: 'sb29806003vo'
  }
};
function nextTick(findObj, tick) {
  function doIt() {
    var obj = findObj();
    if (!obj) {
      setTimeout(() => {
        nextTick(findObj);
      }, 200);
    }
  }
  if (tick) {
    setTimeout(doIt, tick);
  } else {
    doIt();
  }
}

// 印花税
const isReport = async (type) => {
  return new Promise((reslove, reject) => {
    nextTick(() => {
      let lis = $('#sxtable tbody tr');
      if (lis.length > 1) {
        let lisArr = Array.from(lis);
        let report = lisArr.find((item) => $(item).find('td:nth-child(2)').text().includes(type));
        let result = $(report).find('td:nth-child(7) div').text().includes('申报');
        let yhs = window.sessionStorage.getItem('yhs');
        if (result && !yhs) reslove(report);
        else reslove(false);
        return true;
      }
    });
  });
};

const btnInit = async (btn_init, mainIframe) => {
  btn_init.click();
  return asyncSetInterval(() => {
    let aBtn = mainIframe.contents().find('.xubox_layer > .xubox_main > .xubox_botton > .xubox_yes');
    if (aBtn.length) {
      aBtn[0].click();
      return true;
    }
  }, 1000).then(() => {
    return asyncSetInterval(() => {
      let aBtn = mainIframe.contents().find('.xubox_layer > .xubox_main > .xubox_botton > .xubox_yes');
      if (aBtn.length) {
        aBtn[0].click();
        return true;
      }
    }, 2000);
  });
};

const handelYHS = async (currentZeroInfo) => {
  asyncSetInterval(() => {
    let contentiframe = $('#contentiframe');
    if (contentiframe.length) {
      return contentiframe;
    }
  }, 2000).then((contentiframe) => {
    // 是否为再次申报
    let n = 0;
    return asyncSetInterval(() => {
      let xubox_layer = contentiframe.contents().find('.xubox_layer');
      if (xubox_layer.length) {
        let trs = xubox_layer.find('div.dialogtablebox > table > tbody > tr');
        let yhsItme = Array.from(trs).find(item => $(item).find('td:nth-child(3)').text().includes('印花税申报'));
        if (yhsItme && $(yhsItme).find('td:nth-child(6)').text().includes('申报成功')) {
          window.sessionStorage.setItem('yhs', true);
          currentToTaxindex({
            step: 1,
            isclose: false,
            type: 'yhs'
          });
          setTimeout(() => {
            window.close();
          }, 500);
        } else if (yhsItme) {
          $(yhsItme).find('td:nth-child(1) input').click();
          return contentiframe.contents().find(' div.tablebtns > input:nth-child(1)');
        }
      }
      n++;
      if (n > 2) {
        return contentiframe.contents().find('#ente_home');
      }
    }, 2000);
  }).then(subBtn => {
    return asyncSetInterval(() => {
      subBtn.click();
      return true;
    }, 1000);
  }).then(() => {
    return asyncSetInterval(() => {
      let contentiframe = $('#contentiframe');
      if (contentiframe.length) {
        let mainIframe = contentiframe.contents().find('#mainIframe');
        if (mainIframe.length) {
          return mainIframe;
        }
      }
    }, 1000);
  })
    .then(async (mainIframe) => {
      let btn_init = mainIframe.contents().find('#btn_init');
      if (btn_init.length) {
        await btnInit(btn_init, mainIframe);
      }
      // mainIframe[0].contentWindow.refreshContrl();
      return asyncSetInterval(() => {
        mainIframe = $('#contentiframe').contents().find('#mainIframe');
        let loadingBox = mainIframe.contents().find('#loading-box');
        if (!loadingBox.length && mainIframe.length) {
          let lis = mainIframe.contents().find('#btsblb > ul > li');
          if (lis && lis.length) return lis;
        }
      }, 2000);
    })
    .then(lis => {
      lis.find('a > span.action').click();
      return asyncSetInterval(() => {
        let mainIframe = $('#contentiframe').contents().find('#mainIframe');
        if (mainIframe.length && mainIframe.contents().find('title').text() === '印花税纳税申报（报告）表') {
          return mainIframe;
        }
      }, 1000);
    })
    .then(mainIframe => {
      return asyncSetInterval(() => {
        mainIframe.contents().find('input[name="sqr"]').val(currentZeroInfo.corporationName);
        mainIframe.contents().find('input[name="dlrsfzjhm"]').val(currentZeroInfo.corporationIdcard);
        return mainIframe;
      }, 2000);
    })
    .then(async (mainIframe) => {
      mainIframe.contents().find('#save_btn').click();
      await btnClickSure(mainIframe);
      return true;
    })
    .then(() => {
      return asyncSetInterval(() => {
        let mainIframe = $('#contentiframe').contents().find('#mainIframe');
        if (mainIframe.length) {
          let mainWindow = mainIframe[0].contentDocument;
          mainWindow.querySelector('#goback_btn').click();
          return true;
        }
      }, 1000);
    })
    .then(() => {
      return asyncSetInterval(() => {
        let mainIframe = $('#contentiframe').contents().find('#mainIframe');
        let loadingBox = mainIframe.contents().find('#loading-box');
        if (!loadingBox.length && mainIframe.length) {
          if (mainIframe.contents().find('input[name="sbbt"]').length) {
            let refreshBtn = mainIframe.contents().find('input[name="refreshBtn"]');
            if (refreshBtn.val().includes('刷')) {
              mainIframe.contents().find('input[name="sbbt"]').click();
              return true;
            }
          }
        }
      }, 1000);
    })
    .then(() => {
      return asyncSetInterval(() => {
        let mainIframe = $('#contentiframe').contents().find('#mainIframe');
        let loadingBox = mainIframe.contents().find('#loading-box');
        if (mainIframe.length && !loadingBox.length) {
          let xubox_yes = mainIframe.contents().find('.xubox_layer > .xubox_main > .xubox_botton > .xubox_yes');
          if (xubox_yes.length) {
            xubox_yes[0].click();
            return true;
          }
        }
      }, 1000);
    })
    .then(() => {
      return asyncSetInterval(() => {
        let mainIframe = $('#contentiframe').contents().find('#mainIframe');
        mainIframe[0].contentWindow.refreshContrl();
        let sbstate = mainIframe.contents().find('.sbstate');
        if (sbstate.length && sbstate.text().includes('申报成功')) {
          window.sessionStorage.setItem('yhs', true);
          return true;
        }
      }, 10000);
    })
    .then(() => {
      // 同步明细表
      return asyncSetInterval(() => {
        let mainIframe = $('#contentiframe').contents().find('#mainIframe');
        let loadingBox = mainIframe.contents().find('#loading-box');
        if (!loadingBox.length && mainIframe.length) {
          let lis = mainIframe.contents().find('#btsblb > ul > li');
          if (lis && lis.length) return lis;
        }
      });
    })
    .then((lis) => {
      lis.find('a > span.action').click();
      return asyncSetInterval(() => {
        let mainIframe = $('#contentiframe').contents().find('#mainIframe');
        let loadingBox = mainIframe.contents().find('#loading-box');
        if (!loadingBox.length && mainIframe.length) {
          let html1 = mainIframe.contents().find('body > div.dbt');
          let html2 = mainIframe.contents().find('body > table');
          let htmlTable = Array.from(html2).reduce((c, item) => c + item.outerHTML, html1[0].outerHTML);
          let tableContent = {
            declareType: '印花税申报',
            title: html1.text(),
            html: htmlTable,
            css: ''
          };
          // console.log(tableContent);
          saveTableDetail(tableContent);
          setTimeout(() => {
            currentToTaxindex({
              step: 1,
              isclose: true,
              type: 'yhs'
            });
          }, 1000);
          return true;
        }
      }, 2000);
    });
};

// 印花税确定按钮点击
const btnClickSure = async (mainIframe) => {
  return asyncSetInterval(() => {
    let aBtn = mainIframe.contents().find('.xubox_layer > .xubox_main > .xubox_botton > .xubox_yes');
    if (aBtn.length) {
      aBtn[0].click();
      return true;
    }
  });
};

// 是否需要申报财务报表
const isReprotCwbb = async () => {
  return new Promise((reslove, reject) => {
    nextTick(() => {
      let lis = $('#sxtable tbody tr');
      if (lis.length > 1) {
        let lisArr = Array.from(lis);
        let isCwbb = Boolean(window.sessionStorage.getItem('isCwbb'));
        if (isCwbb) reslove(!isCwbb);
        let cwbb = lisArr.find((item) => $(item).find('td:nth-child(2)').text().includes('财务报表月(季)申报'));
        reslove(
          !!cwbb
            && !!$(cwbb).find('td:nth-child(7) div').text().includes('申报')
        );
        return true;
      }
    });
  });
};

const handelCwbb1 = (currentZeroInfo) => {
  zeroInfo = currentZeroInfo;
  let li = Array.from($('#sxtable tbody tr')).find((item) =>
    $(item).find('td:nth-child(2)').text().includes('财务报表月(季)申报'));
  // 判断会计准则、报税时间是否一致
  let kjzz = $(li).find('td:nth-child(2)').text();
  let kssj = $(li).find('td:nth-child(3)').text().split('-');
  let jssj = $(li).find('td:nth-child(4)').text().split('-');
  if (
    kjzz.includes(kjzzDm[currentZeroInfo.companyType])
    && currentZeroInfo.year === parseInt(kssj[0])
    && (currentZeroInfo.beginPeriod === parseInt(kssj[1]) || currentZeroInfo.beginPeriod === (parseInt(kssj[1]) + 1))
    && currentZeroInfo.endPeriod === parseInt(jssj[1])
  ) {
    let reportBtn = $(li).find('td:nth-child(7) div');
    if (reportBtn.text() === '申报') {
      reportBtn.click();
      nextTick(() => {
        window.postMessage(
          {
            event: 'closeTabs'
          },
          '*'
        );
        return true;
      }, 1000);
    }
  } else {
    // console.log(parseInt(kssj[0]), parseInt(kssj[1]), parseInt(jssj[1]));
    window.postMessage({
      event: 'zeroReportFail',
      data: {
        message: '企业会计准则或者报税时间错误，请更正后再申报'
      }
    }, '*');
  }
};
const handleStep11 = (currentZeroInfo) => {
  zeroInfo = currentZeroInfo;
  nextTick(() => {
    if ($('#ente_home').length) {
      $('#ente_home').click();
      handleStep12();
      return true;
    }
  }, 500);
};
const handleStep12 = () => {
  nextTick(() => {
    let listIframe = $('#mainIframe');
    if (listIframe.length) {
      listIframe.onload = handleStep13(listIframe);
      return true;
    }
  }, 500);
};
const handleStep13 = (listIframe) => {
  nextTick(() => {
    let btsblb = listIframe.contents().find('#btsblb > ul > li');
    if (btsblb.length) {
      let zcfzbFix = Array.from(btsblb).find((item) =>
        $(item).text().includes('利润表'));
      handleZcfzb($(zcfzbFix));
      return true;
    }
  });
};
const handleZcfzb = (optionBtn) => {
  optionBtn.find('.action').click();
  nextTick(() => {
    let tableContent = $('#mainIframe');
    if (tableContent.length) {
      tableContent.onload = openTable();
      return true;
    }
  }, 2000);
};
const openTable = async () => {
  let result1 = await writeTable('zcfzb');
  let result2 = await writeTable('lrb');
  let result3 = await writeTable('xjllb');
  if (result1 && result2 && result3) {
    // 返回申报
    let iframeWindow = $('#mainIframe').contents();
    let goback_btn = iframeWindow.find('#goback_btn');
    goback_btn.click();
    nextTick(() => {
      let mainIframe = $('#mainIframe').contents();
      let sbbtn = mainIframe.find('#sbbtn');
      if (sbbtn.length) {
        console.log(sbbtn);
        sbbtn.click();
        window.sessionStorage.setItem('isCwbb', 'true');
        window.location.href = 'https://etax.jiangsu.chinatax.gov.cn/portal/index.do';
        return true;
      }
    });
  } else {
    window.postMessage(
      {
        event: 'zeroReportFail',
        data: {
          success: false,
          message: '财务报表报税失败了'
        }
      },
      '*'
    );
  }
};
const writeTable = async (writeType) => {
  let li = await changeBb(writeType);
  $(li).click();
  return new Promise((reslove, reject) => {
    let iframeWindow = $('#mainIframe');
    let insType = zeroInfo.companyType === 3 ? 'xqykjzz' : 'qykjzz';
    let workData = zeroInfo.cwbbInfo[writeType];
    let prefix = inputIds[insType][writeType];
    let data = cwbbData[insType][writeType];
    let keys = Object.keys(data);
    let isWorkEmpty = keys.find(item => {
      let cell = workData[data[item]];
      return parseFloat(cell.qmye) || parseFloat(cell.ncye) || parseFloat(cell.bnljje) || parseFloat(cell.bqje);
    });
    if (writeType === 'zcfzb') {
      nextTick(async () => {
        console.log(iframeWindow.contents().find('body > div.dbt').text());
        if (
          iframeWindow.contents().find('body > div.dbt')
          && iframeWindow.contents().find('body > div.dbt').text().includes('资产负债表')
        ) {
          if (isWorkEmpty) {
            keys.forEach((item) => {
              let cId = `#${prefix}\\.${item}`;
              let cellNumber = data[item];
              let cell = workData[cellNumber];
              let value = item.includes('qmye') ? cell.qmye : cell.ncye;
              iframeWindow.contents()
                .find(cId)
                .val(parseFloat(value))
                .trigger('change');
            });
          }
          iframeWindow.contents().find('#jbrxxTab input[name="sqr"]').val(zeroInfo.corporationName);
          iframeWindow.contents().find('#jbrxxTab input[name="dlrsfzjhm"]').val(zeroInfo.corporationIdcard);
          let issuccess = await saveBtnClick(iframeWindow);
          if (issuccess) reslove(true);
          else {
            reslove(false);
          }
          return true;
        }
      }, 500);
    }
    if (writeType === 'lrb') {
      nextTick(async () => {
        if (
          iframeWindow.contents().find('body > div.dbt')
          && iframeWindow.contents().find('body > div.dbt').text().includes('利润表')
        ) {
          if (isWorkEmpty) {
            keys.reverse().forEach((item) => {
              let cId = `#${prefix}\\.${item}`;
              let cellNumber = data[item];
              let cell = workData[cellNumber];
              let value = item.includes('bnljje') ? cell.bnljje : cell.bqje;
              iframeWindow.contents()
                .find(cId)
                .val(parseFloat(value))
                .trigger('change');
            });
          }
          let issuccess = await saveBtnClick(iframeWindow);
          if (issuccess) reslove(true);
          else {
            reslove(false);
          }
          return true;
        }
      }, 500);
    }
    if (writeType === 'xjllb') {
      nextTick(async () => {
        if (
          iframeWindow.contents().find('body > div.dbt')
          && iframeWindow.contents().find('body > div.dbt').text().includes('现金流量表')
        ) {
          if (isWorkEmpty) {
            keys.reverse().forEach((item) => {
              let cId = `#${prefix}\\.${item}`;
              let cellNumber = data[item];
              let cell = workData[cellNumber];
              let value = item.includes('bnljje') ? cell.bnljje : cell.bqje;
              iframeWindow.contents()
                .find(cId)
                .val(parseFloat(value))
                .trigger('change');
            });
          }
          let issuccess = await saveBtnClick(iframeWindow);
          if (issuccess) reslove(true);
          else {
            reslove(false);
          }
          return true;
        }
      }, 500);
    }
  });
};
// 保存按钮
const saveBtnClick = async (iframeWindow) => {
  return new Promise((reslove, reject) => {
    setTimeout(() => {
      iframeWindow.contents().find('#save_btn').click();
      nextTick(() => {
        let diaLog = iframeWindow.contents().find('div.xubox_layer');
        if (diaLog.length) {
          console.log(diaLog);
          if (diaLog.find('div.xubox_main > div.xubox_dialog > span').text().includes('保存成功')) {
            iframeWindow.contents().find('div.xubox_layer > div.xubox_main > span.xubox_botton > a')[0].click();
            reslove(true);
          } else {
            reslove(false);
          }
          return true;
        }
      });
    }, 500);
  });
};
async function changeBb(type) {
  // 切换报表
  let iframeWindow = $('#mainIframe')[0].contentWindow;
  return new Promise(reslove => {
    let timer = setInterval(() => {
      let btn = iframeWindow.$('#chooseBB_btn');
      if (btn.length) {
        btn.click();
        let lis = Array.from(iframeWindow.$('#selectSub > table > tbody > tr'));
        if (lis.length) {
          clearInterval(timer);
          timer = null;
          reslove(lis.find((item) => $(item).text().includes(bbType[type])));
          // return ;
        }
      }
    }, 1000);
  });
}

export {
  handelCwbb1, isReprotCwbb, handleStep11, isReport, handelYHS
};
